package com.example.supernote.ui.note.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.example.supernote.R
import com.example.supernote.model.note.context.Context
import com.example.supernote.ui.components.UniformDialog
import com.example.supernote.ui.components.UniformDropMenu
import com.example.supernote.ui.components.UniformPreviewBody
import com.example.supernote.ui.components.UniformPreviewFooter
import com.example.supernote.ui.components.UniformProgressBar
import com.example.supernote.ui.components.UniformToast
import com.example.supernote.ui.note.utils.getFinalTemplate
import com.example.supernote.ui.utils.getShowInfos

// 获取所选文本
fun getSelectedContext(context: Context): String {
    val start = context.selection.min
    val end = context.selection.max
    return context.article.text.substring(start, end).trim()
}

@Composable
fun ShowAiDialog(
    onCancel: () -> Unit,
    onGenerate: ((String) -> Unit, Map<String, String>) -> Unit,
    onConfirm: (aiCode: String) -> Unit,
    changeContextRange: () -> Unit = {},
    context: Context,
    otherInfos: Map<String, String>
) {
    // 上下文环境
    val toastContext = LocalContext.current
    // 配置信息：otherInfos
    val dialogTitle = otherInfos["dialogTitle"]!!
    val isTranslateMode = dialogTitle == stringResource(R.string.note_translation)
    val showInfos = getShowInfos(dialogTitle)
    val isPolishText = showInfos["aiMode"]!! == stringResource(R.string.note_polish)
    // 用户选择的文本
    var curText by remember { mutableStateOf(getSelectedContext(context)) }
    // 是否选择了文本
    var showWarnDialog by remember { mutableStateOf(curText.trim().isEmpty()) }
    // 语言配置
    val languageOptions = mapOf(
        "中文" to "zh-CHS",
        "英文" to "en",
        "日文" to "ja",
        "韩文" to "ko"
    )
    var fromLanguage by remember { mutableStateOf("中文") }
    var targetLanguage by remember { mutableStateOf("英文") }

    if (showWarnDialog) {
        val textWarn = stringResource(R.string.note_text_warning)
        UniformDialog(
            title = dialogTitle,
            cancelButtonText = stringResource(R.string.note_to_select),
            confirmButtonText = stringResource(R.string.note_article),
            onCancel = {
                showWarnDialog = false
                onCancel()
            },
            onConfirm = {
                curText = context.article.text.trim()
                if (isPolishText)
                    changeContextRange()
                showWarnDialog = curText.isEmpty()
                if (showWarnDialog) {
                    UniformToast(toastContext, textWarn)
                }
            },
            body = {
                Box(
                    contentAlignment = Alignment.Center,
                    modifier = Modifier.padding(10.dp)
                ) {
                    Text(
                        text = stringResource(R.string.note_ai_tip),
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
            }
        )
    } else if (curText.isNotEmpty()) {
        if (isTranslateMode && curText.length > 1200) {
            UniformToast(toastContext, stringResource(R.string.note_translate_warning))
            onCancel()
        } else {
            var isGenerated by remember { mutableStateOf(false) }
            var template by remember { mutableStateOf("") }

            UniformDialog(
                title = dialogTitle,
                body = {
                    val getHtml: @Composable () -> String = {
                        val ctx = Context(selection = TextRange(0, context.article.text.length))
                        ctx.article =
                            if (template.isEmpty()) TextFieldValue(curText) else TextFieldValue(
                                getFinalTemplate(template)
                            )
                        if (!isTranslateMode) ctx.parseContext()
                        else ctx.article.text
                    }
                    UniformPreviewBody(
                        title = if (template == "") stringResource(R.string.note_preview_select) else stringResource(
                            R.string.note_preview_result
                        ),
                        html = getHtml()
                    )
                    if (isGenerated) {
                        UniformProgressBar(showInfos["progressInfo"]!!, "liner")
                    } else if (isTranslateMode) {
                        Row(
                            modifier = Modifier.height(40.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text("from: ")
                            UniformDropMenu(
                                buttonModifier = Modifier.weight(1f),
                                menuItems = languageOptions,
                                menuButtonEnabled = !isGenerated,
                                menuButtonText = fromLanguage
                            ) { key, _ ->
                                fromLanguage = key
                            }
                            Spacer(modifier = Modifier.weight(1f))
                            Text("to: ")
                            UniformDropMenu(
                                buttonModifier = Modifier.weight(1f),
                                menuItems = languageOptions,
                                menuButtonEnabled = !isGenerated,
                                menuButtonText = targetLanguage
                            ) { key, _ ->
                                targetLanguage = key
                            }
                        }
                    }
                }
            ) {
                // footer
                UniformPreviewFooter(
                    template = getFinalTemplate(template),
                    isGenerated = isGenerated,
                    aiMode = showInfos["aiMode"]!!,
                    confirmButtonText = showInfos["confirmButtonText"]!!,
                    onCancel = onCancel,
                    onConfirm = {
                        onConfirm(template)
                        UniformToast(toastContext, showInfos["resultTip"]!!)
                    }
                ) {
                    // onGenerate()
                    template = ""
                    isGenerated = true
                    onGenerate(
                        {
                            template = it
                            isGenerated = false
                        },
                        mapOf(
                            "prompt" to curText,
                            "systemPrompt" to otherInfos["systemPrompt"]!!,
                            "from" to languageOptions[fromLanguage]!!,
                            "target" to languageOptions[targetLanguage]!!,
                            "text" to curText
                        )
                    )
                }
            }
        }
    }
}
